﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using AnalisisDeRiesgos.Dal;

namespace AnalisisDeRiesgos.Models.User
{
    public class LogOnModel
    {
        [DisplayName("Nombre de usuario")]
        [Required(ErrorMessage="El nombre de usuario es requerido")]
        [StringLength(50, ErrorMessage = "El nombre de usuario debe ser máximo de 10 caracteres")]
        [RegularExpression(@"^[a-zA-Z0-9]+$", ErrorMessage = "El nombre debe ser solo letras o números")]
        public String UserName { get; set; }

        [DisplayName("Contraseña")]
        [DataType(DataType.Password)]
        [Required(ErrorMessage="La contraseña es requerida")]
        [StringLength(50, ErrorMessage = "La contraseña escrita es invalida", MinimumLength = 6)]
        public String Password { get; set; }

        public int GetUserId()
        {
            if (ValidateUser())
            {
                riskanalysisEntities entities = new riskanalysisEntities();
                var theUser = (from user in entities.users
                               where user.username == UserName
                               select new { user.username, user.CI }).First();

                return theUser.CI;
            }
            else
                return 0;
        }

        private bool ValidateUser()
        {
            riskanalysisEntities entities = new riskanalysisEntities();
            var resp = from user in entities.users
                       where user.username == UserName && user.enabled
                       select new { user.username, user.password };
            if (resp.Count() <= 0)
                return false;
            var theUser = resp.First();

            if (theUser != null)
            {
                if (Utils.CalculateSHA1(Password) != theUser.password)
                    return false;
                return true;
            }
            else
                return false;
        }
    }
}